package com.ironone.mediaplayerdemo;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;


public class MyMediaPlayerService extends Service {

	BroadcastReceiver br_ConnectivityCheck;
	BroadcastReceiver br_HeadsetCheck;
	BroadcastReceiver br_commonReceiver;
	
	
	@Override
	public void onCreate() {
		try {
			super.onCreate();
			MyMediaPlayer.getMediaPlayerAudioFocus(getApplicationContext());
			
			br_ConnectivityCheck = new BroadcastReceiver(){
				@Override
				public void onReceive(Context context, Intent intent) {
					boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
					if (noConnectivity) {
						if (MyMediaPlayer.getIsPlayerOnBackground()) {  // Player not on top of screen
							//MyMediaPlayer.resetMediaPlayer();
							//MyMediaPlayer.prepareMediaPlayer();
							MyMediaPlayer.resetAndPrepareMediaPlayer();
						} else {
							Intent intent1 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
							intent1.putExtra(MyMediaPlayer.VALUE, MyMediaPlayerServiceNotifyStatus.connectivity.ordinal()); // value == 0
							sendBroadcast(intent1);
						}
					}
				}
			};
			registerReceiver(br_ConnectivityCheck, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

			br_HeadsetCheck = new BroadcastReceiver(){
				@Override
				public void onReceive(Context context, Intent intent) {
					int state = intent.getIntExtra("state", 0);
					switch (state) {
					case 0: // Headset is unplugged					
						if (MyMediaPlayer.getIsPlayerOnBackground()) {  // Player not on top of screen
							MyMediaPlayer.pauseMediaPlayer();
						} else {
							Intent intent2 = new Intent(MyMediaPlayer.SVC_NOTIFICATION);
							intent2.putExtra(MyMediaPlayer.VALUE, MyMediaPlayerServiceNotifyStatus.headsetUnmonted.ordinal()); // value == 1
							sendBroadcast(intent2);
						}
						break;
					case 1: // Headset is plugged
						break;
					default:
					}
				}
			};
			registerReceiver(br_HeadsetCheck, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
			
			myMediaPlayerActivityCallbacks();
		} catch (Exception e) {
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(br_ConnectivityCheck);
		unregisterReceiver(br_HeadsetCheck);
		unregisterReceiver(br_commonReceiver);
	}


	private void myMediaPlayerActivityCallbacks() {
		try {
			br_commonReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					int value = intent.getIntExtra("value", -1);

					switch (value) {
					case 0 : // MyMediaPlayerServiceNotifyStatus.connectivity
						//MyMediaPlayer.resetMediaPlayer();
						//textViewLoading.setText("no network");
						//playButton.setChecked(false);
						//startLoading();
						//MyMediaPlayer.prepareMediaPlayer();
						MyMediaPlayer.resetAndPrepareMediaPlayer();
						break;

					case 1 : // MyMediaPlayerServiceNotifyStatus.headsetunmonted
						if(MyMediaPlayer.getMediaPlayerInstance().isPlaying()){
							//playButton.setChecked(false);
							//textViewLoading.setText("paused");
							MyMediaPlayer.pauseMediaPlayer();
						}
						break;
					case 3: // MyMediaPlayerServiceNotifyStatus.audioFocusLost
						if(MyMediaPlayer.getMediaPlayerInstance().isPlaying()){
							MyMediaPlayer.pauseMediaPlayer();
							//textViewLoading.setText("paused");
							//playButton.setChecked(false);
							//timerToStopPlayback(timerToStopPlayback);
						}
						break;

					default:
						MyMediaPlayer.resetMediaPlayer();
						//textViewLoading.setText("reseted");
						//playButton.setChecked(false);
						break;
					}
				}
			};
			registerReceiver(br_commonReceiver, new IntentFilter(MyMediaPlayer.ACT_NOTIFICATION));
		} catch (Exception e) {
			//stopLoading();
			//playButton.setChecked(false);
			MyMediaPlayer.releaseMediaPlayer();			
		}
	}
}



/*package com.ironone.mediaplayerdemo;

import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;

public class MyMediaPlayerService extends Service {

	String url = "http://198.50.207.172:8000/live.mp3";
	public static MediaPlayer mediaPlayer = new MediaPlayer();
	private boolean isPlaying = false;

	private static int classID = 579; // just a number
	public static String START_PLAY = "START_PLAY";

	public static MediaPlayerStatus mediaPlayerStatus = null;
	int length = 0;

	private NotificationManager mNM;

    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = 1115;


    /**
 * Class for clients to access.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with
 * IPC.
 */
/*@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // Display a notification about us starting.  We put an icon in the status bar.
        //showNotification();

        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
			public void onPrepared(MediaPlayer mp) {
				//ToggleButton playButton = (ToggleButton) findViewById(R.id.togglebutton);
				mediaPlayerStatus = MediaPlayerStatus.playing;
				//loading.clearAnimation();
				//loading.setVisibility(View.INVISIBLE);
				mp.start();
			}
		});

    }

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent.getBooleanExtra(START_PLAY, false)) {
			play();
		}
		return Service.START_STICKY;	
	}

	private void play() {
		if (!isPlaying)       
			isPlaying = true;

		/*Intent intent = new Intent(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
					Intent.FLAG_ACTIVITY_SINGLE_TOP);*/

//PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

/*Notification notification = new Notification.Builder(getApplicationContext())
			.setContentTitle("My Music Player")
			.setContentText("Now Playing: \"Rain\"")
			.setSmallIcon(R.drawable.ic_launcher)
			.setContentIntent(pi)
			.build();*/

//mediaPlayer = MediaPlayer.create(this, R.raw.rain); // change this for your file
//mediaPlayer.setLooping(true); // this will make it loop forever
//mediaPlayer.start();
/*if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
		}
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepareAsync();
		} catch (IllegalArgumentException e) {
			Toast.makeText(getApplicationContext(),"111111",Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (IllegalStateException e) {
			Toast.makeText(getApplicationContext(),"222222",Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (IOException e) {
			Toast.makeText(getApplicationContext(),"333333",Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		//startForeground(classID, notification);
	}

	@Override
	public void onDestroy() {
		stop();
	}	

	private void stop() {
		if (isPlaying) {
			isPlaying = false;
			if (mediaPlayer != null) {
				mediaPlayer.release();
				mediaPlayer = null;
			}
			stopForeground(true);
		}
	}
}*/
